﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

namespace Trade.Journal
{


    public static class DataShop
    {

        public delegate void RecordsChangedHandler();
        public static event RecordsChangedHandler RecordsChanged;


        public static Record[] Records => DataCollection.ToArray();

        private static HashSet<Record> DataCollection { get; set; }


        static DataShop()
        {
            DataCollection = new HashSet<Record>(DbHelper.LoadAll());
        }

        public static void LoadRecord(string id)
        {
            DataCollection.Add(DbHelper.LoadRecord(id));
            RecordsChanged?.Invoke();
        }

        public static void Remove(string id)
        {
            DataCollection.RemoveWhere(x => x.Id == id);
            RecordsChanged?.Invoke(); 
        }

        internal static RoadMap GetRoadmap(string recordId)
        {
            return new RoadMap(DataCollection.Where(x => x.GroupId == recordId).Select(x=>new RoadMapNode { RecordId = x.Id, Content = GetEnumDescription(x.OpenDeal.TradeType)}));
        }

        public static string GetEnumDescription(Enum e)
        {
            System.Reflection.FieldInfo field = e.GetType().GetField(e.ToString());
            object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (objs.Length == 0)
                return string.Empty;
            DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
            return descriptionAttribute.Description;
        }
    }

    public struct RoadMapNode
    {
        public string Content { get; set; }

        public string RecordId { get; set; }
         

    }

    public class RoadMap : ObservableCollection<RoadMapNode>
    {
        public RoadMap(Record record)
        {
            Add(new RoadMapNode { Content = "首次入场", RecordId = record.Id });
        }

        public RoadMap(IEnumerable<RoadMapNode > collection) 
        {
            if (collection != null && collection.Any())
            {
                foreach (var item in collection)
                {
                    var node = new RoadMapNode { RecordId = item.RecordId };
                    if (Count == 0)
                        node.Content = "首次入场";
                    else
                        node.Content = item.Content;

                    Add(node);
                }
            }
        }
    }
}
